package com.pickgliss.utils
{
	import com.pickgliss.events.InteractiveEvent;
	
	import flash.display.InteractiveObject;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	/**
	 * 
	 * @author James
	 * 
	 */
	public final class DoubleClickManager
	{
		private static var _instance:DoubleClickManager;
		
		private const DoubleClickSpeed:uint = 350;
		
		private var _timer:Timer;
		private var _currentTarget:InteractiveObject;
		private var _ctrlKey:Boolean;
		
		public function DoubleClickManager(){
			init();
		}
		
		/**
		 * 
		 * 获得此类的实例
		 * 
		 * @return 
		 * 
		 */		
		public static function get Instance():DoubleClickManager{
			if(!_instance){
				_instance = new DoubleClickManager();
			}
			
			return _instance;
		}
		
		/**
		 * 
		 * 开启组件双击，需要监听 InteractiveEvent.CLICK 和 InteractiveEvent.DOUBLE_CLICK 事件
		 * 
		 * @param target 需要监听双击事件的对象
		 * 
		 */		
		public function enableDoubleClick(target:InteractiveObject):void{
			target.addEventListener(MouseEvent.MOUSE_DOWN, __mouseDownHandler);
		}
		
		/**
		 * 
		 * 关闭组件双击，需要移除 InteractiveEvent.CLICK 和 InteractiveEvent.DOUBLE_CLICK 事件
		 * 
		 * @param target 需要移除双击事件的对象
		 * 
		 */	
		public function disableDoubleClick(target:InteractiveObject):void{
			target.removeEventListener(MouseEvent.MOUSE_DOWN, __mouseDownHandler);
		}
		
		private function init():void{
			_timer = new Timer(DoubleClickSpeed, 1);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, __timerCompleteHandler);
		}
		
		private function getEvent(type:String):InteractiveEvent{
			var interactiveEvent:InteractiveEvent = new InteractiveEvent(type);
			interactiveEvent.ctrlKey = _ctrlKey;
			
			return interactiveEvent;
		}
		
		private function __timerCompleteHandler(evt:TimerEvent):void{
			_currentTarget.dispatchEvent(getEvent(InteractiveEvent.CLICK));
		}
		
		private function __mouseDownHandler(evt:MouseEvent):void{
			_ctrlKey = evt.ctrlKey;
			
			if(_timer.running){
				_timer.stop();
				
				if(_currentTarget != evt.currentTarget){
					return;
				}
				evt.stopImmediatePropagation();
				_currentTarget.dispatchEvent(getEvent(InteractiveEvent.DOUBLE_CLICK));
			}else{
				_timer.reset();
				_timer.start();
				_currentTarget = evt.currentTarget as InteractiveObject;
			}
		}
		
		public function clearTarget():void
		{
			if(_timer) _timer.stop();
			_currentTarget = null;
		}
	}
}